package com.fastjrun.xxl.job.api.helper;

import com.fastjrun.xxl.job.api.common.ScheduleTypeEnum;
import com.fastjrun.xxl.job.api.dto.XxlJobInfoDTO;
import com.fastjrun.xxl.job.api.entity.XxlJobInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** @author xuxueli 2019-05-21 */
public class JobScheduleHelper {
  private static Logger logger = LoggerFactory.getLogger(JobScheduleHelper.class);

  private static JobScheduleHelper instance = new JobScheduleHelper();

  public static JobScheduleHelper getInstance() {
    return instance;
  }

  public static final long PRE_READ_MS = 5000; // pre read

  private Thread scheduleThread;
  private Thread ringThread;
  private volatile boolean scheduleThreadToStop = false;
  private volatile boolean ringThreadToStop = false;
  private static volatile Map<Integer, List<Integer>> ringData = new ConcurrentHashMap<>();

  // ---------------------- tools ----------------------
  public static Date generateNextValidTime(XxlJobInfo xxlJobInfo, Date fromTime) throws Exception {
    ScheduleTypeEnum scheduleTypeEnum = ScheduleTypeEnum.match(xxlJobInfo.getScheduleType(), null);
    if (ScheduleTypeEnum.CRON == scheduleTypeEnum) {
      Date nextValidTime =
          new CronExpression(xxlJobInfo.getScheduleConf()).getNextValidTimeAfter(fromTime);
      return nextValidTime;
    } else if (ScheduleTypeEnum.FIX_RATE
        == scheduleTypeEnum /*|| ScheduleTypeEnum.FIX_DELAY == scheduleTypeEnum*/) {
      return new Date(fromTime.getTime() + Integer.valueOf(xxlJobInfo.getScheduleConf()) * 1000);
    }
    return null;
  }
}
